from model.Course import Course
from controller.Base import BaseHandler
from tornado import gen
import datetime


class CourseHandler(BaseHandler):
    @gen.coroutine
    def get(self, *args, **kwargs):
        id = self.session.get("id")
        cate = self.session.get("cate")
        if cate is None:
            return self.write(self.response_code.USER_NOT_LOGGED_IN)
        resp = self.response_code.SUCCESS.copy()
        if cate == 0:
            data = yield Course.get_by_sid(id)
        elif cate == 1:
            data = yield Course.get_by_tid(id)
        else:
            return self.write(self.response_code.USER_NOT_LOGGED_IN)
        resp["data"] = data
        resp["total"] = len(data)
        return self.write(resp)

    @gen.coroutine
    def post(self, *args, **kwargs):
        cate = self.session.get("cate", -1)
        id = self.session.get('id')
        if cate == 1:
            # 教师端,创建课程, 并排到数据库中
            try:
                c_id = self.get_argument("cid", "")
                c_name = self.get_argument("cname")
                start_week = self.get_argument("start")
                end_week = self.get_argument("end")
                # day 星期几 : 1-7
                c_day = self.get_argument("day")
                c_number = self.get_argument("number")
                c_place = self.get_argument("place")
            except Exception as e:
                return self.write(self.response_code.PARAM_NOT_COMPLETE)
            # 验证参数格式:
            if not "{}{}{}{}{}".format(start_week, end_week, c_day, c_number, c_id).isdigit():
                return self.write(self.response_code.PARAM_TYPE_BIND_ERROR)
            start_week, end_week, c_day, c_number = int(start_week), int(end_week), int(c_day), int(c_number)

            if c_id == "":
                # 第一次添加课程,自动分配c_id
                c_id = yield Course.get_max_c_id()
                c_id = int(c_id) + 1

            """ 1.创建用户组 """
            self.face_client.groupAdd(c_id)

            # 开学日期,星期一
            term_begin_date = datetime.date(2019, 3, 25)
            for week in range(start_week - 1, end_week):
                c_data = term_begin_date + datetime.timedelta(days=c_day, weeks=week)
                result = yield Course.add(c_name, c_data, c_number, id, c_day, c_place, start_week, end_week,
                                          term_begin_date, c_id)
                if not result:
                    return self.write(self.response_code.SYSTEM_BUSY_ERROR)

        elif cate == 0:
            # 学生端,通过绑定某项课程,在数据库record表中,增加多条学生待上课记录
            c_id = self.get_argument("cid")

            """ 2.将学生记录复制添加到用户组中"""
            s_id = self.session.get("id")
            s_class = self.session['class']
            options = {"src_group_id": s_class, "dst_group_id": c_id}
            self.face_client.userCopy(s_id, options)

            result = yield Course.add_bind_to_cid_for_student(id, c_id)
            if not result:
                return self.write(self.response_code.COURSE_NOT_EXIST)
        else:
            return self.write(self.response_code.PARAM_IS_INVALID)

        return self.write(self.response_code.SUCCESS)

    @gen.coroutine
    def put(self, *args, **kwargs):
        pass

    @gen.coroutine
    def delete(self, *args, **kwargs):
        if self.session.get("cate", 0) != 1:
            return self.write(self.response_code.PARAM_IS_INVALID)
        try:
            c_id = self.get_argument("cid")
        except Exception as e:
            return self.write(self.response_code.PARAM_NOT_COMPLETE)

        result = yield Course.del_by_cid(c_id)
        if result == True:
            return self.write(self.response_code.SUCCESS)
        else:
            return self.write(self.response_code.SYSTEM_BUSY_ERROR)
